package com.nx.platform.entry.filter;

import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

import javax.servlet.DispatcherType;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * filterName = "filter1" 用来置顶 filter 的执行顺序, 文字排序
 * 跨域问题解决
 */
@WebFilter(urlPatterns = {"/*"}, dispatcherTypes = {DispatcherType.REQUEST}, filterName = "filter1")
public class CorsFilter implements Filter {
    private static final String ALLOWED_HOST = "http://m.naixuejiaoyu.com";
    
    public static final String ALLOWED_HOST_HTTPS = "https://m.naixuejiaoyu.com";
    
    private static final Set<String> ALLOWED_HOST_SET = new HashSet<String>(); // 允许跨域访问的域名
    
    static {
        ALLOWED_HOST_SET.add("http://api.naixuejiaoyu.com");
    }
    
    @Override
    public void init(FilterConfig filterConfig)
        throws ServletException {
    }
    
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
        HttpServletRequest httpReq = (HttpServletRequest)request;
        HttpServletResponse httpResp = (HttpServletResponse)response;
        
        // 容许Cookie跨域，做Session检查
        httpResp.addHeader("Access-Control-Allow-Credentials", "true");
        if (httpReq.getMethod().equalsIgnoreCase("options")) {
            // 探测请求
            String originalUrl = httpReq.getHeader("Origin");
            if (null != originalUrl && (ALLOWED_HOST_SET.contains(originalUrl))) { // 跨域白名单
                httpResp.addHeader("Access-Control-Allow-Origin", httpReq.getHeader("Origin"));
            } else {
                httpResp.addHeader("Access-Control-Allow-Origin", ALLOWED_HOST);
            }
            httpResp.addHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS");
            httpResp.addHeader("Access-Control-Max-Age", "3600");
            httpResp.addHeader("Content-Type", "text/plain");
            return;
        } else {
            chain.doFilter(request, response);
        }
    }
    
    @Override
    public void destroy() {
    }
}
